package com.yinxing.webapi.shiro;

import com.yinxing.framework.constant.SysConstant;
import com.yinxing.framework.shiro.jwt.JwtToken;
import com.yinxing.framework.utils.JwtUtils;
import com.yinxing.webapi.code.service.sys.ISysUserService;
import com.yinxing.webapi.config.AppConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class JwtLoginRealm extends AuthenticatingRealm {

    @Autowired
    private AppConfig appConfig;

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) token;
        //获取jwt-token
        String tokenStr = jwtToken.getPrincipal().toString();

        //用秘钥验证token
        boolean verify = JwtUtils.verify(tokenStr, appConfig.getJwtSecure());
        if(!verify) {
            throw new AuthenticationException("jwtToken invalid");
        }

        //读取用户ID
        String userId = JwtUtils.getValue(tokenStr, SysConstant.JWT_TOKEN_DATA_USERID);

        //获取当前用户身份信息
        LoginUser loginUser = sysUserService.createloginUser(Long.valueOf(userId), jwtToken.getHost());
        if(loginUser == null) {
            throw new AuthenticationException(String.format("用户ID{%s}查询不到用户信息", userId));
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(loginUser, tokenStr, getName());
        return info;
    }
}
